package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/models"
	"strconv"
	"time"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}

	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.Work{}).Count(&count)

	var work []models.Work
	redis_key := "work_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"work":  work,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var work models.Work
	redis_key := "work_list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": work,
	})
	return
}
